import Scanner from './Scanner'
import nestTokens from './nestTokens';

export default function parseTemplateToToken(templateStr) {
  let tokens = [], words;
  let scanner = new Scanner(templateStr)

  while (!scanner.eos()) {
    words = scanner.scanUtil('{{')
    if (words != '') {
      // 去空格
      let isInJJH = false
      let _words = ''
      for (let i = 0; i < words.length; i++) {
        // 判断是否在标签里
        if (words[i] == '<') {
          isInJJH = true
        } else if (words[i] == '>') {
          isInJJH = false
        }

        if (words[i] != ' ') { //如果该项不是空格
          _words += words[i] //保存该项
        } else { //如果空格
          if (isInJJH) { //如果在标签中
            _words += words[i] //保存该项
          }
        }
      }
      tokens.push(['text', _words])
    }
    scanner.scan('{{')
    words = scanner.scanUtil('}}')
    if (words != '') {
      if (words[0] == '#') {
        tokens.push(['#', words.substr(1)])
      } else if (words[0] == '/') {
        tokens.push(['/', words.substr(1)])
      } else {
        tokens.push(['name', words])
      }
    }
    scanner.scan('}}')
  }
  return nestTokens(tokens)
}